package edu.tamu.cse.lenss.sensor;


import edu.tamu.cse.lenss.utils.Logger;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class LocationController {
	private static final String TAG = LocationController.class.getSimpleName();
	private LocationManager locationManager;
	private LocationProvider provider;
	private long updatePeriod;
	private float accuracy=99999;
	private Context context;
	private LocationControllerListener listener;
	
	public enum LocationProvider{
		GPS, NETWORK;

		@Override
		public String toString() {
			if(this.equals(GPS))
				return LocationManager.GPS_PROVIDER;
			else if(this.equals(NETWORK))
				return LocationManager.NETWORK_PROVIDER;
			else
				return null;
		}
	}
	
	public LocationController(LocationProvider provider, int period, LocationControllerListener listener, Context context){
		this.provider = provider;
		this.updatePeriod =period;
		this.context = context;
		this.listener = listener;
		this.locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
	}
	
	public void setAccuracy(float accu){
		if(accu <=0)
			this.accuracy = 99999;
		else
			this.accuracy = accu;
	}
	
	public void startUpdateLocation(){
		locationManager.requestLocationUpdates(provider.toString(), updatePeriod, 0, locationListener);
	}
	
	public void stopUpdateLocation(){
		locationManager.removeUpdates(locationListener);
	}
	
	private LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			if(location.getAccuracy() > accuracy)
				return;
			
			Logger.v(TAG, "New Location Updated from " + location.getProvider());
			listener.onNewUpdate(location);
		}

		public void onProviderDisabled(String provider) {
			Logger.e(TAG, provider + " is disabled");
			listener.onError(provider + " is disabled");
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	};
	
	public static interface LocationControllerListener {
				
		void onNewUpdate(Location location);
		void onError(String msg);
	}	
}
